<template>
	<!-- 医院详情页 -->
	<view class="hospital-detail">
	  <!-- 医院图片 -->
	  <image class="hospital-image" :src="hospitalInfo.imgurl" mode="aspectFill" @error="handleImageError"></image>
	  
	  <!-- 医院基本信息 -->
	  <view class="hospital-info">
	    <view class="hospital-time">正常营业 | 周一至周日 08:00-18:00</view>
	    <view class="hospital-tags">
		  <text class="tag">医保定点</text>
		  <text class="tag">三甲医院</text>
		  <text class="tag">预约挂号</text>
		  <text class="tag">全周无休</text>
	    </view>
      <view class="address-row" @click="penLocation"></view>
	    <view class="hospital-address">{{ hospitalInfo.address }}</view>
	  </view>
	
	  <!-- 预约入口 -->
	  <view class="appointment-section">
	    <view class="appointment-item" @click="goToRegister">
	      <!-- <image class="icon" src="/images/register.png"></image> -->
	      <text>门诊预约</text>
	    </view>
	    <view class="appointment-item" @click="goToExam">
	      <!-- <image class="icon" src="/images/exam.png"></image> -->
	      <text>体检预约</text>
	    </view>
	  </view>
	
	  <!-- 名医专家 -->
	  <view class="doctors-section">
	    <view class="section-header">
	      <text class="section-title">名医专家</text>
	      <view class="view-more" @tap="goToDoctorList">
	        <text>查看更多</text>
	        <text class="arrow">></text>
	      </view>
	    </view>
	    <view class="doctors-list">
	      <view class="doctor-item" v-for="doctor in displayDoctors" :key="doctor.id" @click="goToDoctorDetail(doctor)">
	        <image class="doctor-img" :src="doctor.imgurl" mode="aspectFill"></image>
	        <view class="doctor-info">
	          <view class="doctor-name">{{ doctor.name }}</view>
	          <view class="doctor-title">{{ doctor.title }}</view>
	          <view class="doctor-dept">{{ doctor.department }}</view>
	          <view class="doctor-specialty">{{ doctor.desc }}</view>
	        </view>
	      </view>
	    </view>
	  </view>
	
<!-- 	  患者评价
	  <view class="reviews-section">
	    <view class="section-title">
	      <text>患者评价</text>
	      <text class="review-count">({{ reviewCount }})</text>
	    </view>
	    评价列表
	  </view> -->
	</view>
</template>

<script>
	import { hospitalApi } from '@/api/hospital'
	export default {
	  data() {
	    return {
	      hospitalInfo: {
	        name: '',
	        imgurl: '',
	        address: '',
	        tags: []
	      },
	      doctors: [],
	      hospitalId: null,
	      reviewCount: 142
	    }
	  },
	
	  computed: {
	    displayDoctors() {
	      return this.doctors.slice(0, 2) // 只显示前两个医生
	    }
	  },
	
	  onLoad(options) {
	    console.log('接收到的参数:', options)
	    const hospitalId = options.id
	    if (hospitalId) {
	      this.hospitalId = hospitalId
	      console.log('设置医院ID:', this.hospitalId)
	      this.getHospitalDetail(hospitalId)
	      this.getDoctorsByHospital(hospitalId)
	    } else {
	      console.error('未接收到医院ID')
	      uni.showToast({
	        title: '医院ID不存在',
	        icon: 'none'
	      })
	    }
	  },
	  
	  methods: {
	    getHospitalDetail(id) {
	      console.log('开始获取医院详情, id:', id)
	      
	      uni.request({
	        url: `http://localhost:8090/hospital/${id}`,
	        method: 'GET',
	        success: (res) => {
	          console.log('获取医院详情成功:', res)
	          if (res.statusCode === 200 && res.data.code === 200) {
	            const hospital = res.data.data
	            // 设置页面标题为医院名称
	            if (hospital.name) {
	              uni.setNavigationBarTitle({
	                title: hospital.name
	              })
	            }
	            // 获取医院的地址信息
	            this.getAddressById(hospital.addressId, hospital)
	          } else {
	            uni.showToast({
	              title: res.data.msg || '获取医院详情失败',
	              icon: 'none'
	            })
	          }
	        },
	        fail: (err) => {
	          console.error('获取医院详情请求失败:', err)
	          uni.showToast({
	            title: '网络请求失败',
	            icon: 'none'
	          })
	        }
	      })
	    },
	
	    // 根据ID获取地址信息
	    getAddressById(addressId, hospital) {
	      console.log('开始获取地址信息, addressId:', addressId)
	      
	      uni.request({
	        url: `http://localhost:8090/address/${addressId}`,
	        method: 'GET',
	        success: (res) => {
	          console.log('获取地址信息成功:', res)
	          if (res.statusCode === 200 && res.data.code === 200) {
	            const address = res.data.data
	            // 更新医院信息
	            this.hospitalInfo = {
	              id: hospital.id,
	              name: hospital.name,
	              address: `${address.province}${address.city}${address.district}${address.detailedAddress}`,
	              tags: ['医院', `医生数量: ${hospital.doctorsNum}`],
	              imgurl: hospital.imgurl
	            }
	          } else {
	            this.hospitalInfo = {
	              ...hospital,
	              address: '地址未知'
	            }
	          }
	        },
	        fail: (err) => {
	          console.error(`获取地址ID ${addressId} 失败:`, err)
	          this.hospitalInfo = {
	            ...hospital,
	            address: '地址未知'
	          }
	        }
	      })
	    },
	
      
	    // 处理图片加载错误
	    handleImageError() {
	      console.error('医院图片加载失败:', this.hospitalInfo.imgurl)
	      this.hospitalInfo.imgurl = '/static/images/hospital.png'
	    },
	
	    goToRegister() {
	      console.log('跳转到科室列表，当前医院ID:', this.hospitalId)
	      if (!this.hospitalId) {
	        uni.showToast({
	          title: '医院信息未加载完成',
	          icon: 'none'
	        })
	        return
	      }
	      uni.navigateTo({
	        url: `/pages/department/department?id=${this.hospitalId}`
	      })
	    },
	
	    goToExam() {
	      uni.navigateTo({
	        url: '/pages/checkup/package-list'
	      })
	    },
	
	    // 获取医院的医生列表
	    getDoctorsByHospital(hospitalId) {
	      console.log('开始获取医院医生列表, hospitalId:', hospitalId)
	      const queryPageBean = {
					hospitalId: this.hospitalId,
					currentPage: 1,
					pageSize: 10
				};
	      uni.request({
	        url: `http://localhost:8090/hospital/findDocByHospitalId`,
	        method: 'POST',
			data: queryPageBean,
			header: {
				'Content-Type': 'application/json'
			},
	        success: (res) => {
	          console.log('获取医生列表成功，原始数据:', res.data)
	          if (res.data && res.data.rows) {
	            const doctorsData = res.data.rows || []
	            console.log('医生数据处理前:', doctorsData)
	            
	            // 处理每个医生的数据
	            Promise.all(doctorsData.map(doctor => {
	              return new Promise((resolve) => {
	                // 如果有科室ID，获取科室详情
	                if (doctor.departmentId) {
	                  this.getDepartmentInfo(doctor.departmentId).then(depInfo => {
	                    const mappedDoctor = {
	                      id: doctor.id,
	                      name: doctor.name,
	                      imgurl: doctor.avatar || doctor.imgurl || '/static/images/doctor.png',
	                      title: doctor.position || doctor.title || '主任医师',
	                      department: depInfo?.name || '暂无科室信息',
	                      desc: doctor.tags?.join('、') || doctor.desc || '暂无描述信息'
	                    }
	                    resolve(mappedDoctor)
	                  })
	                } else {
	                  const mappedDoctor = {
	                    id: doctor.id,
	                    name: doctor.name,
	                    imgurl: doctor.avatar || doctor.imgurl || '/static/images/doctor.png',
	                    title: doctor.position || doctor.title || '主任医师',
	                    department: '暂无科室信息',
	                    desc: doctor.tags?.join('、') || doctor.desc || '暂无描述信息'
	                  }
	                  resolve(mappedDoctor)
	                }
	              })
	            })).then(doctors => {
	              this.doctors = doctors
	              console.log('最终的医生列表:', this.doctors)
	            })
	          } else {
	            console.error('获取医生列表失败:', res.data)
	            uni.showToast({
	              title: '获取医生列表失败',
	              icon: 'none'
	            })
	          }
	        },
	        fail: (err) => {
	          console.error('获取医生列表请求失败:', err)
	          uni.showToast({
	            title: '网络请求失败',
	            icon: 'none'
	          })
	        }
	      })
	    },

	    // 获取科室详情
	    getDepartmentInfo(depId) {
	      return new Promise((resolve) => {
	        uni.request({
	          url: `http://localhost:8090/dep/${depId}`,
	          method: 'GET',
	          success: (res) => {
	            if (res.statusCode === 200 && res.data.code === 200) {
	              resolve(res.data.data)
	            } else {
	              console.error('获取科室详情失败:', res)
	              resolve(null)
	            }
	          },
	          fail: (err) => {
	            console.error('获取科室详情请求失败:', err)
	            resolve(null)
	          }
	        })
	      })
	    },

      // 打开地图
      openLocation() {
        uni.openLocation({
            latitude: 39.9087, // 默认经纬度，应该从API获取
            longitude: 116.3975,
            name: this.hospital.name,
            address: this.hospital.fullAddress,
          success: () => {
            console.log('打开地图成功')
          },
          fail: (err) => {
              console.error('打开地图失败:', err)
              uni.showToast({
              title: '打开地图失败',
              icon: 'none'
            })
          }
        })
      },


	    // 跳转到医生列表页面
	    goToDoctorList() {
	      uni.navigateTo({
	        url: `/pages/doctor/list?hospitalId=${this.hospitalId}`
	      })
	    },

      // 跳转到医生详情页
      goToDoctorDetail(doctor) {
        uni.navigateTo({
          url: `/pages/doctor/docList?id=${doctor.id}&department=${encodeURIComponent(doctor.department)}`,
          fail: (err) => {
            console.error('跳转失败:', err);
            uni.showToast({
              title: '页面跳转失败',
              icon: 'none'
            });
          }
        });
      }
	  }
	}
</script>

<style>
.hospital-detail {
  background: #f5f5f5;
  min-height: 100vh;
}

.hospital-image {
  width: 100%;
  height: 200px;
}

.hospital-info {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.hospital-name {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.hospital-tags {
  display: flex;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.tag {
  font-size: 24rpx;
  color: #07c160;
  background: rgba(7, 193, 96, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.hospital-address {
  font-size: 28rpx;
  color: #666;
}

.appointment-section {
  display: flex;
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.appointment-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
}

.appointment-item .icon {
  width: 60rpx;
  height: 60rpx;
}

.appointment-item text {
  font-size: 28rpx;
  color: #333;
}

.doctors-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
}

.view-more {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.view-more text {
  font-size: 28rpx;
  color: #666;
}

.arrow {
  font-size: 28rpx;
  color: #666;
}

.doctors-list {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.doctor-item {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
}

.doctor-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  flex: 0 0 160rpx; /* 固定宽度，不伸缩 */
  object-fit: cover;
}

.doctor-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10rpx 0;
}

.doctor-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
  color: #333;
}

.doctor-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.doctor-dept {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.doctor-specialty {
  font-size: 26rpx;
  color: #999;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.reviews-section {
  background: #fff;
  padding: 30rpx;
}

.review-count {
  font-size: 28rpx;
  color: #999;
  font-weight: normal;
  margin-left: 8rpx;
}
</style>
